package com.stars.easyms.alarm.client.wechat;

import com.alibaba.fastjson.JSON;
import com.stars.easyms.alarm.message.EasyMsAlarmMessage;
import com.stars.easyms.alarm.client.EasyMsAlarmClient;
import com.stars.easyms.alarm.constant.EasyMsAlarmConstant;
import com.stars.easyms.alarm.factory.AlarmRestTemplateFactory;
import com.stars.easyms.alarm.properties.EasyMsAlarmProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;

import java.util.Map;
import java.util.stream.Stream;

/**
 * <p>className: EasyMsWeChatAlarmClient</p>
 * <p>description: 企业微信告警客户端</p>
 *
 * @author caotieshuan
 * @version 1.5.0
 * @date 2019-12-18 16:21
 */
@Slf4j
public class EasyMsWeChatAlarmClient implements EasyMsAlarmClient {

    private EasyMsAlarmProperties.WeChat weChatAlarmProperties;

    private String[] postUrls;

    public EasyMsWeChatAlarmClient(EasyMsAlarmProperties alarmProperties) {
        this.weChatAlarmProperties = alarmProperties.getWeChat();
    }

    @Override
    public void sendAlarmMessage(EasyMsAlarmMessage easyMsAlarmMessage) {
        for (String postUrl : postUrls) {
            Map<String, Object> requestData = this.getMarkdownMessage(easyMsAlarmMessage.getContext());
            ResponseEntity<Object> response = AlarmRestTemplateFactory.getRestTemplate().postForEntity(postUrl, requestData, Object.class);
            if (log.isDebugEnabled()) {
                log.debug("EnterpriseWeChat sendMsg result：{}", JSON.toJSONString(response));
            }
        }
    }

    @Override
    public String getClientType() {
        return EasyMsAlarmConstant.WECHAT;
    }

    @Override
    public boolean initAndReturnIsValid() {
        if (weChatAlarmProperties.isEnabled()) {
            if (StringUtils.isNotBlank(weChatAlarmProperties.getRobotUrl())) {
                this.postUrls = Stream.of(weChatAlarmProperties.getRobotUrl().split(",")).map(String::trim).toArray(value -> new String[0]);
                return true;
            }
            log.error("Easy-ms {} alarm client: RobotUrl is null", getClientType());
        }
        return false;
    }

    /**
     * 发送消息封装 markdown类型
     */
    private Map<String, Object> getMarkdownMessage(String message) {
        MarkdownMessage markdownMessage = new MarkdownMessage();
        markdownMessage.add(markdownMessage.getReferenceText(message));
        return markdownMessage.toMessageMap();
    }
}
